/**
 * Created by GUO on 2017/5/19.
 * @flow
 * 周刊
 */

import React from 'react';
import {
    View,
    Text,
    StyleSheet,
    Image,
    Platform,
    ActivityIndicator,
    SectionList,
} from 'react-native';
import BaseScreen from '../BaseScreen';
import Icon from 'react-native-vector-icons/MaterialIcons';
import HttpClient from '../HttpClient';
import WeeklyItem from './WeeklyItem';
import WeeklySection from './WeeklySection';

const styles = StyleSheet.create({
    container:{
        flex:1,
        alignItems:'center',
        justifyContent:'center',
    },
    titleBarIcon:{
        paddingHorizontal:10,
    },
});

export default class WeeklyScreen extends BaseScreen {

    static navigationOptions = {
        title: '周刊',
        tabBarIcon: ({ tintColor }) => (
            <Icon size={26} color={tintColor} name="explore"/>
        ),
        headerRight:(<Icon
            name="settings"
            size={24}
            color="white"
            style={styles.titleBarIcon}/>)
    };

    state = {
        sections:[],
        fetching: true,
        refreshing: false,
    };

    _fetchData(){
        HttpClient.get('/mag/home.json').then(response => {

            let { items } = response.data;
            let sections = items.map(item => ({
                key: String(item.type),
                type: item.type,
                name: item.name,
                data:[...item.items]
            }));

            this.setState({
                fetching:false,
                refreshing:false,
                sections
            });

        }).catch(e => {
            this.setState({
                fetching:false
            });
            console.log('=err====>>',e);
        });
    }

    componentDidMount(){
        this._fetchData();
    }

    render(){
        if(this.state.fetching){
            return <ActivityIndicator/>
        }else if(this.state.sections.length>0){
            return <SectionList
                initialNumToRender = {12}
                keyExtractor = {(item,index) => item.id}
                onRefresh={()=> this.setState({refreshing:true},()=>this._fetchData(true))}
                refreshing={this.state.refreshing}
                stickySectionHeadersEnabled = {false}
                style={{flex:1}}
                sections = {this.state.sections}
                renderSectionHeader={this._renderSection.bind(this)}
                renderItem = {this._renderItem.bind(this)}
            />
        }else{
            return <Text>数据为空／超时</Text>
        }
    }

    _renderSection({section}){
        return <WeeklySection
            onPress={()=>this._onPressSection(section)}
            data={section}
        />
    }

    _onPressSection(section){

    }

    _renderItem({item}){
        return <WeeklyItem data={item}/>
    }
}

